// +build ignore

package main

import (
	"context"
	"log"

	"gitlab.com/gitlab-org/gitaly/v14/internal/git"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/repository"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/archive"
	archiveservice "gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/service/archive"
	repositoryservice "gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/service/repository"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/rubyserver"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/transaction"
	"gitlab.com/gitlab-org/gitaly/v14/internal/storage"
	"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
)

// Example: How to integrate Archive Housekeeping with Repository Service
// This example shows how to configure and use the archive housekeeping feature
// within the repository service to automatically check for expired refs during
// optimization and garbage collection operations.

func ExampleArchiveHousekeepingIntegration() {
	// Configuration setup
	cfg := config.Cfg{
		// ... your gitaly configuration
	}

	// Initialize required dependencies
	locator := config.NewLocator(cfg)
	gitCmdFactory := git.NewExecCommandFactory(cfg)
	catfileCache := catfile.NewCache(cfg)
	rubyServer := &rubyserver.Server{} // Initialize properly
	txManager := &transaction.Manager{} // Initialize properly

	// Archive-related components
	storageManager := archive.NewStorageManager(locator)
	gitOperations := archive.NewGitOperations(gitCmdFactory)
	lockManager := archive.NewLockManager(archive.LockConfig{
		LockDir: "/tmp/gitaly-locks", // Configure lock directory
		Timeout: 30000,               // 30 seconds timeout
	})

	// Kafka producer for archive tasks (optional)
	var kafkaProducer *archiveservice.KafkaProducer
	if cfg.ArchiveKafka != nil && cfg.ArchiveKafka.Enabled {
		kafkaProducer = archiveservice.NewKafkaProducer(*cfg.ArchiveKafka)
		defer kafkaProducer.Close()
	}

	// Housekeeping configuration
	housekeepingConfig := archiveservice.HousekeepingConfig{
		Enabled:                   true,
		KeepAroundRetentionDays:   30, // Archive keep-around refs after 30 days
		MergeRequestRetentionDays: 90, // Archive MR refs after 90 days
		APIEndpoint:               "https://gitlab.example.com/api/v4", // For MR status checks
		APIToken:                  "your-api-token", // API access token
	}

	// Create archive housekeeping integration
	housekeepingIntegration := archiveservice.NewHousekeepingIntegration(
		cfg,
		locator,
		gitCmdFactory,
		storageManager,
		gitOperations,
		kafkaProducer,
		housekeepingConfig,
		lockManager,
	)

	// Create repository service with archive integration
	repositoryServer := repositoryservice.NewServerWithArchive(
		cfg,
		rubyServer,
		locator,
		txManager,
		gitCmdFactory,
		catfileCache,
		housekeepingIntegration, // Pass the housekeeping integration
	)

	log.Printf("Repository service with archive housekeeping integration created successfully")

	// The repository service will now automatically check for expired archive refs
	// during optimization operations (repack, garbage collection, etc.)

	// Example: Manually trigger expired refs check for a specific repository
	repo := &gitalypb.Repository{
		StorageName:  "default",
		RelativePath: "example/repository.git",
	}

	if gitRepo := repository.NewFromGitaly(repo, gitCmdFactory, catfileCache, locator); gitRepo != nil {
		if err := housekeepingIntegration.CheckExpiredRefs(context.Background(), gitRepo); err != nil {
			log.Printf("Failed to check expired refs: %v", err)
		} else {
			log.Printf("Successfully checked expired refs for repository")
		}
	}
}

// Example configuration for archive housekeeping in gitaly config.toml:
//
// [archive]
//   enabled = true
//   storage_path = "/var/opt/gitlab/git-data/archive"
//
// [archive.housekeeping]
//   enabled = true
//   keep_around_retention_days = 30
//   merge_request_retention_days = 90
//   api_endpoint = "https://gitlab.example.com/api/v4"
//   api_token = "your-gitlab-api-token"
//
// [archive.kafka]
//   enabled = true
//   brokers = ["localhost:9092"]
//   topic = "gitaly-archive-tasks"
//   consumer_group = "gitaly-archive-consumer"

// Key Integration Points:
//
// 1. Repository Optimization (repack operations):
//    - The repository service calls CheckExpiredRefs before performing repack
//    - Expired refs are automatically queued for archival
//    - This prevents archiving refs that are about to be repacked
//
// 2. Garbage Collection:
//    - Similar integration during GC operations
//    - Ensures ref cleanup happens before object cleanup
//
// 3. Automatic Processing:
//    - New refs discovered during housekeeping are written to waiting metadata
//    - Expired refs trigger Kafka messages for background processing
//    - Lock mechanism prevents concurrent housekeeping runs
//
// 4. Different Expiration Logic:
//    - keep-around refs: expire based on commit creation time
//    - merge-requests refs: expire based on MR merge time (via API)
//    - branches: expire based on last commit time
//    - tags: expire based on tag creation time
//
// 5. Error Handling:
//    - Housekeeping errors don't fail the main repository operations
//    - Failed archive operations are logged and retried via Kafka
//    - Lock conflicts are handled gracefully (skip if already running)
